package top.hidoctor.auscultation.feature.fragment.patient;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.widget.DrawerLayout;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.gson.reflect.TypeToken;
import com.tang.util.GsonUtil;
import com.tang.util.SPUtil;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import top.hidoctor.auscultation.R;
import top.hidoctor.auscultation.adapter.PatientAdapter;
import top.hidoctor.auscultation.adapter.ShaixuanAdapter;
import top.hidoctor.auscultation.base.BaseFragment;
import top.hidoctor.auscultation.base.Constant;
import top.hidoctor.auscultation.bean.PatientLocalInfo;
import top.hidoctor.auscultation.bean.PatientsBean;
import top.hidoctor.auscultation.bean.ShaixuanBean;
import top.hidoctor.auscultation.event.PatientEvent;
import top.hidoctor.auscultation.event.XinyinEvent;
import top.hidoctor.auscultation.feature.activity.AddPatientActivity;
import top.hidoctor.auscultation.feature.activity.PatientActivity;
import top.hidoctor.auscultation.net.c.PatientContract;
import top.hidoctor.auscultation.net.p.PatientPresenter;
import top.hidoctor.auscultation.net.req.PetientReq;

public class PatientFragment extends BaseFragment implements View.OnClickListener, PatientContract.View {

    private ImageButton ibAddPatient;
    private RecyclerView recycler, rcCondition;
    private PatientAdapter adapter;
    private PatientPresenter presenter;
    private PetientReq pageReq;
    private SwipeRefreshLayout refreshLayout;
    private EditText editSearch;
    private DrawerLayout drawer;
    private TextView tvShaixuan, tvList, tvBangding;
    private List<ShaixuanBean> shaixuanBeanList = new ArrayList<>();
    private Button btnChongzhi, btnConfirm;
    private ShaixuanAdapter shaixuanAdapter;
    private ImageButton ibBack;
    private String from;
    private PatientLocalInfo info;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_patient, container, false);
        return view;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        EventBus.getDefault().register(this);

        presenter = new PatientPresenter(getContext(), this);
        pageReq = new PetientReq();
        initView();
        initEvent();
    }

    private void initEvent() {
        if (getArguments() != null) {
            from = getArguments().getString("from");
            info = (PatientLocalInfo) getArguments().getSerializable("info");
            if (from != null && !TextUtils.isEmpty(from) && from.equals("caiji")) {
                tvBangding.setVisibility(View.VISIBLE);
                tvList.setVisibility(View.GONE);
                ibBack.setVisibility(View.VISIBLE);
                ibBack.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        getActivity().finish();
                    }
                });
            }
        } else {
            tvBangding.setVisibility(View.GONE);
            tvList.setVisibility(View.VISIBLE);
            ibBack.setVisibility(View.GONE);
        }

        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(mContext);
        adapter = new PatientAdapter(R.layout.item_patient, null);
        recycler.setLayoutManager(linearLayoutManager);
        recycler.setAdapter(adapter);
        View view = LayoutInflater.from(getContext()).inflate(R.layout.layout_empty_list, (ViewGroup) recycler.getParent(), false);
        adapter.setEmptyView(view);
        adapter.isFirstOnly(false);
        adapter.openLoadAnimation();
        adapter.openLoadMore(10, true);
        adapter.setOnLoadMoreListener(new BaseQuickAdapter.RequestLoadMoreListener() {
            @Override
            public void onLoadMoreRequested() {
                loadMore();
            }
        });
        refreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                hideSoft(recycler);
                pageReq.setKeyWord(editSearch.getText().toString().trim());
                refresh();
            }
        });
        adapter.setOnRecyclerViewItemClickListener(new BaseQuickAdapter.OnRecyclerViewItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                if (!TextUtils.isEmpty(from) && from.equals("caiji")) {
                    String content = (String) SPUtil.get(getContext(), Constant.LOCAL_INFO, "");
                    if (!TextUtils.isEmpty(content)) {
                        List<PatientLocalInfo> data = GsonUtil.parseJson(content, new TypeToken<List<PatientLocalInfo>>() {
                        });
                        for (int i = 0; i < data.size(); i++) {
                            if (data.get(i).getFileName().equals(info.getFileName())) {
                                data.get(i).setUserId(adapter.getData().get(position).getId());
                                break;
                            }
                        }
                        SPUtil.put(getContext(), Constant.LOCAL_INFO, GsonUtil.toJsonStr(data));
                        showToast("绑定成功");
                        EventBus.getDefault().post(new XinyinEvent());
                        getActivity().finish();
                    }
                } else {
                    Intent intent = new Intent(getContext(), PatientActivity.class);
                    intent.putExtra("info", adapter.getData().get(position));
                    startActivity(intent);
                }
            }
        });
        editSearch.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {

                //以下方法防止两次发送请求
                if (actionId == EditorInfo.IME_ACTION_SEND ||
                        (event != null && event.getKeyCode() == KeyEvent.KEYCODE_ENTER)) {
                    switch (event.getAction()) {
                        case KeyEvent.ACTION_UP:
                            //发送请求
                            pageReq.setKeyWord(v.getText().toString().trim());
                            refresh();
                            return true;
                        default:
                            return true;
                    }
                }
                return false;
            }
        });

        refresh();
    }

    private void loadMore() {
        pageReq.setPageNo(1 + pageReq.getPageNo());
        presenter.getList(pageReq, refreshLayout);
    }

    private void refresh() {
        pageReq.setPageNo(1);
        presenter.getList(pageReq, refreshLayout);
    }

    private void initView() {
        ibAddPatient = getActivity().findViewById(R.id.ib_add_patient);
        recycler = getActivity().findViewById(R.id.recycler);
        editSearch = getActivity().findViewById(R.id.edit_search);
        tvShaixuan = getActivity().findViewById(R.id.tv_shaixuan);
        refreshLayout = getActivity().findViewById(R.id.refreshLayout);
        ibBack = getActivity().findViewById(R.id.ib_back);
        tvList = getActivity().findViewById(R.id.tv_list);
        tvBangding = getActivity().findViewById(R.id.tv_bangding);
        ibAddPatient.setOnClickListener(this);
        tvShaixuan.setOnClickListener(this);
        initDrawer();
    }

    private void initDrawer() {
        shaixuanBeanList.add(new ShaixuanBean(false, "男", "1"));
        shaixuanBeanList.add(new ShaixuanBean(false, "女", "2"));
        drawer = getActivity().findViewById(R.id.drawer);
        rcCondition = getActivity().findViewById(R.id.rc_condition);
        btnChongzhi = getActivity().findViewById(R.id.btn_chongzhi);
        btnConfirm = getActivity().findViewById(R.id.btn_confirm);
        rcCondition.setLayoutManager(new GridLayoutManager(getContext(), 3));
        rcCondition.setAdapter(shaixuanAdapter = new ShaixuanAdapter(R.layout.item_shaixuan, shaixuanBeanList));
        btnConfirm.setOnClickListener(this);
        btnChongzhi.setOnClickListener(this);
        shaixuanAdapter.setOnRecyclerViewItemChildClickListener(new BaseQuickAdapter.OnRecyclerViewItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                List<ShaixuanBean> data = adapter.getData();
                for (int i = 0; i < data.size(); i++) {
                    data.get(i).setCheck(false);
                }
                data.get(position).setCheck(true);
                adapter.notifyDataSetChanged();
                pageReq.setGender(data.get(position).getStatus());
            }
        });
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.ib_add_patient:
                startActivity(new Intent(getContext(), AddPatientActivity.class));
                break;
            case R.id.tv_shaixuan:
                drawer.openDrawer(Gravity.RIGHT);
                break;
            case R.id.btn_chongzhi:
                List<ShaixuanBean> shaixuanList = shaixuanAdapter.getData();
                for (int i = 0; i < shaixuanList.size(); i++) {
                    shaixuanList.get(i).setCheck(false);
                }
                shaixuanAdapter.notifyDataSetChanged();
                drawer.closeDrawer(Gravity.RIGHT);
                editSearch.setText("");
                pageReq.setGender("");
                pageReq.setKeyWord("");
                refresh();
                break;
            case R.id.btn_confirm:
                drawer.closeDrawer(Gravity.RIGHT);
                editSearch.setText("");
                pageReq.setKeyWord("");
                refresh();
                break;
        }
    }


    @Override
    public void getListSuc(PatientsBean bean) {
        if (pageReq.getPageNo() == 1) {
            refreshLayout.setRefreshing(false);
            adapter.setNewData(bean.getResult());
        } else {
            adapter.addData(bean.getResult());
        }
        adapter.openLoadMore(bean.getTotalItems() > adapter.getItemCount());
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(PatientEvent event) {
        refresh();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Override
    public void onError(String code, String msg) {
        super.onError(code, msg);
        refreshLayout.setRefreshing(false);
        showToast(msg);
    }
}
